<?php

	class IndustriesController extends AppController
	{
		
		var $name = 'Industries';
		var $uses = array('Industry', 'IndustryShop');
		
		var $publicAction = array('index', 'details');
		
		var $industry = null;
		var $term = null;
		
		function index()
		{
			$this->Industry->Shop->recursive = -1;
			$shops = $this->Industry->Shop->find(
				'count',
				array(
					'conditions' => array(
						'Shop.deleted' => 0,
						'Shop.disabled' => 0
					),
					'recursive' => -1
				)
			);
			
			$this->set('shops', $shops);
			
			$this->pageTitle = __('Rubros', true);
			
			$this->IndustryShop->Behaviors->attach('Containable');
			$this->IndustryShop->recursive = 1;
			
			$industries = $this->IndustryShop->find(
				'all',
				array(
					'conditions' => array(
						'IndustryShop.deleted' => 0,
						'IndustryShop.disabled' => 0
					),
					'group' => 'industry_id',
					'contain' => array(
						'Industry' => array(
							'Term' => array(
								'fields' => array(),
								'conditions' => array(
									'IndustriesTerm.deleted' => 0
								)
							)
						)
					),
					'order' => 'Industry.name ASC'
				)
			);
			
			$this->set('industries', $industries);
		}
		
		function details($industry = null, $term = null)
		{
			$this->industry = $industry;
			$this->term = $term;
			
			$this->Industry->recursive = -1;
			$data = $this->Industry->findBySlug($this->industry);
			
			$this->pageTitle = $data['Industry']['name'];
						
			$this->set('industry', $data);
			
			if (!is_null($this->industry) AND is_null($this->term)) {
				$this->IndustryShop->unbindModel(
					array(
						'belongsTo' => array(
							'Industry'
						)
					),
					false
				);
				
				$this->paginate = array(
					'limit' => 25,
					'page' => 1,
					'conditions' => array(
						'IndustryShop.deleted' => 0,
						'IndustryShop.disabled' => 0,
						//
						'IndustryShop.industry_id' => $data['Industry']['id']
					)
				);
				
				$this->set('shops', $this->paginate('IndustryShop'));
			}
			elseif (!is_null($this->term)) {
				App::import('Model', array('Term', 'Taxonomy'));
				
				$term = new Term();
				$taxonomy = new Taxonomy();
				
				$term->recursive = -1;
				$data = $term->findBySlug($this->term);
				
				$this->pageTitle = $data['Term']['name'];
				
				$this->set('term', $data);
				
				$taxonomy->unbindModel(
					array(
						'belongsTo' => array(
							'Term'
						),
						'hasAndBelongsToMany' => array(
							'Product'
						)
					)
				);
				
				$data = $taxonomy->find(
					'all',
					array(
						'conditions' => array(
							'Taxonomy.term_id' => $data['Term']['id']
						)
					)
				);
				
				$this->set('shops', $data);
			}
		}
		
	}
	
?>
